<template>
	<view class="coupon-popup">
		<u-popup :mask-close-able='false' v-model="show" mode='bottom' border-radius="20">

			<view class="coupon-popup-title ph20 flex-between align-center">
				<view class="flex-start align-center" style="color: rgba(239, 66, 79, 1);" @click="toAddCoupon">
					<view class="fontw f36 mr5">+</view>
					<view class="f28">兑换码</view>
				</view>
				<view class="f36 flex-center" style="color: rgba(34, 34, 34, 1);margin-left: -40rpx;">
					优惠券
				</view>
				<view @click="close" class="iconfont iconbaseline-close-px"
					style="font-size: 44rpx;color: rgba(204, 204, 204, 1);">
				</view>
			</view>

			<scroll-view class="coupon-popup-body" scroll-y="true" @scrolltolower="getData(true)">
				<template v-if="list.length > 0">
					<view :class="['item',item.disabled ? 'disable' : '']"
						v-for="(item,index) in list" :key='index' @click="checkboxChange(item)">
						<view class="top">
							<view class="item-left flex-column align-center">
								<view class="">
									<text class="f32">￥</text>
									<text class="f64" style="font-weight: bold;">{{parseInt(item.activity_price)}}</text>
								</view>
								<view class="">
									{{item.coupon_type == 1 ? '兑换券' : ''}}
								</view>
							</view>
							<view class="item-right ml20 mr24 flex-between align-center">
								<view class="flex-between  align-center">
									<view class="left">
										<view class="title f28 fontw mb10 no-warp-one ">
											{{item.title}}
										</view>
										<view class="time f22">
											有效期至 {{item.validity_time_end}}
										</view>
									</view>
								</view>
								<view class="right">
									<img v-if="item.disabled" src="../static/disable.png" alt="">
									<img v-if="!item.disabled && item.checked" src="../static/checked.png" alt="">
									<img v-if="!item.disabled && !item.checked" src="../static/checked2.png" alt="">
								</view>
							</view>
						</view>
						<view class="disabled_cause" v-if="item.disabled">
							<image src="../static/coupon_disabled_cause_icon.png" mode=""></image>
							<div class="disabled_cause_text">该券不可用原因：<text>{{item.disabled_cause}}</text></div>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="no-coupn flex-center align-end pb40">
						<text class="f24" style="color: rgba(153, 153, 153, 1);">您还没有优惠卷哦</text>
					</view>
				</template>
			</scroll-view>
		</u-popup>
	</view>
</template>

<script>
	import moment from 'moment'
	export default {
		data() {
			return {
				show: false,
				select: '',
				province: '',
				list: [],
				total: 0,
				condition: {
					page: 1,
					pagesize: 10,
				},
				isLoad: true,
				ableNum: 0
			}
		},
		model: {
			prop: 'value',
			event: 'input'
		},
		props: {
			value: {
				type: Boolean,
				default: false
			},
			originaCost: {
				type: Number,
				default: 0
			},
			orderObj: {
				type: Object,
				default: () => {}
			}
		},
		watch: {
			value: {
				handler(val) {
					this.show = val
				},
				immediate: true
			}
		},

		async mounted() {
			await this.getProvince()
			this.getData()
		},
		methods: {
			toAddCoupon(){
				uni.navigateTo({url: '/subpages/coupon/addCoupon'})
			},
			checkboxChange(obj) {
				if (obj.disabled) {
					return
				}
				// ----------------使用的优惠券数量不能超过座位数量---------------
				if(!obj.checked){//点击时选中状态为未选中时
					let couponAvailableQuantity = this.orderObj.count//座位数量
					let nowSelectQuantity = 0//优惠券数量
					this.list.forEach(item =>{//计算已选择的优惠券数量
						if(item.checked == true)nowSelectQuantity++
					})
					if(nowSelectQuantity >= couponAvailableQuantity){
						uni.showToast({
							title:'要使用的优惠券不能超过座位数量',
							icon:'none'
						})
						return
					}
				}
				// ----------------------------------------------------------
				this.$set(obj,'checked',!obj.checked)
				// this.list.forEach(item => {
				// 	if (item.id != obj.id) {
				// 		item.checked = false
				// 	}
				// })
				this.select = obj.checked ? obj.id : ''
			},
			isAble(item) {
				// ----------------判断是否在券的有效时间里----------------------------
				let timeDeadlineBol = this.$common.isBefore(item.validity_time_end)
				if (!timeDeadlineBol) {
					// console.log(item.title, '-timeDeadlineBol-', timeDeadlineBol)
					return [true,'已过有效期']
				}
				// -----------------------------------------------------------------
				// ----------------判断是否在券的有效金额里（优惠券面值是否小于座位的原价）----------------------------
				let costBol = parseFloat(item.activity_price) < parseFloat(this.orderObj.original_price) ? false : true
				if (!costBol) {
					// console.log(item.title, 'costBol有效金额', costBol)
					return [true,'仅限原价'+item.activity_price+'元以下票价使用']
				}
				// ----------------------------------------------------------------------------------------------
				// ----------------判断是否在券的有效影院里----------------------------
				let cinemaBol = this.someEve(item.cinema_name, this.orderObj.cinemaId, 'cinemaid')
				if (!cinemaBol) {
					// console.log(item.title, 'cinemaBol有效影院', cinemaBol)
					return [true,'不支持当前影院']
				}
				// -----------------------------------------------------------------
				// ----------------判断是否在券的有效影厅里----------------------------
				let cinema_hall = item.cinema_halls ? item.cinema_halls.split(',') : ''
				let hallBol = this.someEve(cinema_hall, this.orderObj.hallName)
				// console.log('cinema_hall',cinema_hall)
				// console.log('hallBol',hallBol)
				if (!hallBol) {
					// console.log(item.title, 'hallBol有效影厅', hallBol)
					return [true,'不支持当前影厅']
				}
				// -------------------------------------------------------------------
				// ----------------判断是否在券的有效电影里----------------------------
				let midBol = this.someEve(item.mid, this.orderObj.mid, 'mid')
				if (!midBol) {
					// console.log(item.title, 'midBol有效电影', midBol)
					return [true,'不支持当前影片']
				}
				// -----------------------------------------------------------------
				
				// ----------------判断是否在券的有效省份里----------------------------
				let proBol = this.someEve(item.province, this.province.id, 'id')
				if (!proBol) {
					// console.log(item.title, 'proBol有效省份', proBol)
					return [true,'']
				}
				// ----------------------------------------------------------------------------------------------
				// ----------------判断是否在券的有效城市里----------------------------
				let cityBol = this.someEve(item.city, this.orderObj.cname, 'nm')
				if (!cityBol) {
					// console.log(item.title, 'cityBol有效城市', cityBol)
					return [true,'']
				}
				// -----------------------------------------------------------------
				return false

				// if (timeDeadlineBol && costBol && proBol && cityBol && midBol && cinemaBol && hallBol) {
				// 	return true
				// } else {
				// 	return false
				// }
			},
			someEve(arr, ele, key) {
				if (arr && arr.length > 0) {
					if (key) {
						return arr.some((item) => {
							return item[key] == ele
						})
					} else {
						return arr.some((item) => {
							return item == ele
						})
					}
				} else {
					return true
				}
			},

			getData(status = false) {
				// 全部加载后,不再发送请求
				if (!this.isLoad) {
					return
				}
				// status true:上拉加载，page + 1  ; false : page 重置为 1
				if (status) {
					this.condition.page += 1
				} else {
					this.condition.page = 1
				}
				this.$api.MyCoupon(this.condition).then(res => {
					res = res.data.data
					this.total = res.total

					if (this.list.length > 0) {
						this.list = [...this.list, ...res.data]
					} else {
						this.list = res.data
					}

					this.list.forEach(item => {
						this.$set(item, 'checked', false)
						let result = this.isAble(item)
						item.disabled = result[0]
						item.disabled_cause = result[1]
						

						if (!item.disabled) {
							this.ableNum += 1
						}
						this.ableNum === 0 ? this.$emit('setText', '无可用') : this.$emit('setText',
							`${this.ableNum}张可选`)
					})
					if (this.list.length >= this.total) {
						this.isLoad = false
					}
				}).catch(err => {
					console.log('err', err)
				})
			},

			getProvince() {
				return new Promise((resolve, reject) => {
					this.$api.getProvince({
						cname: this.orderObj.cname
					}).then((res) => {
						this.province = res.data.data
						resolve()
					}).catch((err) => {
						console.log('getProvice err', err)
						resolve()
					})
				})
			},
			clickRadio(item) {
				this.select = item.id
			},
			// 设置payment页面优惠券后方显示的文本
			setText() {
				let text = 0
				let couponItem = []
				this.list.forEach((item)=>{
					if(item.checked){
						text = (Number(text) + Number(this.orderObj.original_price)).toFixed(2)
						couponItem.push(item)
					}
				})
				// console.log(this.select,this.ableNum);
				if (!this.select && couponItem.length == 0) {
					this.ableNum === 0 ? this.$emit('setText', '无可用') : this.$emit('setText', `${this.ableNum}张可选`)
					this.$emit('setItem', '')
					return
				}

				// for (let i = 0; i < this.list.length; i++) {
				// 	let item = this.list[i]
				// 	if (item.id == this.select) {
				// 		// this.$emit('setText', item)
				// 		this.$emit('setText', `${this.originaCost}`)
				// 		this.$emit('setItem', item)
				// 		return
				// 	}
				// }
				this.$emit('setText', `${text}`)
				this.$emit('setItem', couponItem)
			},
			close() {
				this.$emit('input', false)
				this.setText()
			}
		}
	}
</script>


<style lang="scss" scoped>
	.coupon-popup {
		// height: 774rpx;
		// background-color: red;

		.coupon-popup-title {
			height: calc(774rpx - 678rpx);
		}

		.coupon-popup-body {
			height: 678rpx;
			background: #FFFFFF;
			padding: 20rpx;
			
			.item {
				width: 100%;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				overflow: hidden;
				
				>.top {
					display: flex;
					align-items: center;
					justify-content: flex-start;
					width: 100%;
					height: 164rpx;
					background: rgba(255, 67, 69, 0.0400);
					.item-left {
						width: 186rpx;
						height: 100%;
						color: #FF4345;
						background-repeat: no-repeat;
						background-size: 100% 100%;
						border-right: 2rpx dashed #DDC2C3;
					}
					
					.item-right {
						width: calc(100% - 186rpx);
						height: 100%;
					
						.right {
							position: relative;
					
							img {
								width: 40rpx;
								height: 40rpx;
							}
						}
					}
					
					.title {
						color: rgba(34, 34, 34, 1);
					}
					
					.desc {
						color: rgba(102, 102, 102, 1);
					}
					
					.time {
						color: rgba(153, 153, 153, 1);
					}
				}
				
				>.disabled_cause {
					display: flex;
					align-items: center;
					justify-content: flex-start;
					background-color: rgba(255, 67, 69, 0.0400);
					padding: 12rpx 40rpx;
					>image {
						height: 28rpx;
						width: 28rpx;
						margin-right: 8rpx;
					}
					>.disabled_cause_text {
						font-size: 24rpx;
						font-weight: 500;
						color: rgba(255,67,69,0.8);
						line-height: 24rpx;
					}
				}
			}

			.disable {
				.top {
					background: rgba(221, 221, 221, 0.1300);
					.item-left {
						background-image: unset;
						color: #DDDDDD;
						border-color: #DDDDDD;
					}
					
					.title,
					.desc,
					.time {
						color: #DDDDDD;
					}
				}
			}


			.no-coupn {
				margin: 0 auto;
				width: 600rpx;
				height: 450rpx;
				background-image: url(../static/no-coupon.png);
				background-size: 100% 100%;
			}
		}
	}
</style>
